<template>
	<up-popup class="picture-picker-popup" :show="show" safeAreaInsetBottom closeable mode="bottom" round="24rpx"
		@close="$emit('close')" @open="$emit('open')">
		<view class="picture-picker">
			<view class="picture-picker-header">
				<text class="picture-picker-title">{{
          $t("picture.picker.title")
        }}</text>
			</view>
			<view class="picture-picker-column">
				<up-button type="primary" size="large" shape="circle"
					@tap="onPickImage('album')">{{ $t("picture.picker.album") }}</up-button>
				<up-button type="primary" size="large" plain hairline shape="circle"
					@tap="onPickImage('camera')">{{ $t("picture.picker.camera") }}</up-button>
			</view>
		</view>
		<view v-if="hasTabbar" class="tabbar__placeholder"></view>
		<safe-area-insets-bottom />
	</up-popup>
</template>

<script setup>
	import {
		ref
	} from "vue";
	import {
		useI18n
	} from "vue-i18n";
	const {
		t
	} = useI18n();

	defineProps({
		show: Boolean,
		hasTabbar: {
			type: Boolean,
			default: true,
		},
	});
	const emits = defineEmits(["open", "close", "success", "fail"]);

	const onPickImage = async (type) => {
		return new Promise((resolve, reject) => {
			uni.chooseImage({
				count: 1,
				sizeType: ["compressed"],
				sourceType: [type],
				crop: {
					width: 270,
					height: 270,
				},
				success: ({
					tempFilePaths,
					tempFiles
				}) => {
					const [filePath] = tempFilePaths;
					const [file] = tempFiles;
					emits("success", filePath, file);
					resolve(file);
				},
				fail: ({
					code,
					errMsg
				}) => {
					if ([2, 11, 12].includes(Number(code)) && !errMsg.includes(
							'User cancelled')) {
						uni.showModal({
							title: t("common.permissionPrompts"),
							content: `${t("common.pleaseGrant")}${ code === 12 ? t("common.photoAlbum"): t("common.camera")}${t("common.permissionToUseTheFeature")}`,
							confirmText: t("common.goToSettings"),
							cancelText: t("common.cancel"),
							success: (res) => {
								if (res.confirm) {
									uni.openAppAuthorizeSetting();
								}
							},
						});
					}
					emits("fail", err);
					reject(err);
				},
			});
		});
	};
</script>

<style lang="scss" scoped>
	$picture-picker-title-color: #fff !default;

	.picture-picker {
		&-popup {
			:deep(.u-popup__content__close) {
				top: 35rpx;
				right: 35rpx;

				.u-icon__icon {
					color: $picture-picker-title-color !important;
					font-size: 25rpx;
					line-height: 25rpx;
				}
			}
		}

		&-header {
			padding: 32rpx 56rpx;
			text-align: center;
		}

		&-title {
			font-size: 30rpx;
			font-weight: normal;
			line-height: 1;
			color: $picture-picker-title-color;
		}

		&-column {
			padding: 8rpx 56rpx 80rpx;

			& :deep(.u-button):not(:last-child) {
				margin-bottom: 30rpx;
			}
		}
	}

	.tabbar__placeholder {
		height: 100rpx;
	}
</style>